package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderSettingDao orderSettingDao;
    @Autowired
    MemberDao memberDao;

    @Autowired
    OrderDao orderDao;

    /**
     * 添加预约
     *
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Result order(Map map) throws Exception {

        //1.判断用户选择的日期是否可以预约
        String orderDate = (String) map.get("orderDate");
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));

        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2.判断用户选择的日期是否预约已满
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations >= number) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //3.判断是否存在,同一用户同一天预约相同的项目
        String telephone = (String) map.get("telephone");
        //根据手机号,查询该用户是否为会员
        Member member = memberDao.findByTelephone(telephone);

        if (member != null) {//是会员
            //获取会员id
            Integer member_Id = member.getId();
            //获取套餐id
            String setmealId = (String) map.get("setmealId");
            //获取预约时间
            Date date = DateUtils.parseString2Date(orderDate);
            Order order = new Order(member_Id, date, Integer.parseInt(setmealId));

            List<Order> list = orderDao.findByCondition(order);

            if (list != null && list.size() > 0) {
                return new Result(false, MessageConstant.HAS_ORDERED);
            }

        } else {
            //4.判断用户是否为会员,不是会员的话直接注册
            member = new Member();
            member.setName((String) map.get("name"));
            member.setSex((String) map.get("sex"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setRegTime(new Date());

            memberDao.add(member);
        }

        //5.保存预约到数据库
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtils.parseString2Date(orderDate));
        order.setOrderType((String) map.get("orderType"));
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));
        orderDao.add(order);
        //6.预约成功,更改该日期的可预约人数
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);


        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    //根据预约id查看预约详情
    @Override
    public Map findById(Integer id) {
        return orderDao.findById4Detail(id);
    }

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);
        Page<Map> page = orderDao.findByQueryString(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    //添加电话预约
    public Result addOrderByTelephone(Map map, Integer[] setmealIds) throws Exception {

        //1.判断用户选择的日期是否可以预约
        String orderDate = (String) map.get("orderDate");
        Date today = new Date();
        String todayStr = DateUtils.parseDate2String(today);
        int i = orderDate.compareTo(todayStr);
        if (i<0){
            return new Result(false, "请选择"+todayStr+"以后的时间预约");
        }
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));

        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2.判断用户选择的日期是否预约已满
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        int todayOrders = setmealIds.length;//这次请求所选套餐数
        if (reservations >= number) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        int num = number - reservations;//还可预约人数
        if (todayOrders > num) {
            return new Result(false, "今日还可预约" + num + "个套餐");
        }
        //3.判断是否存在,同一用户同一天预约相同的项目
        String telephone = (String) map.get("phoneNumber");
        //根据手机号,查询该用户是否为会员
        Member member = memberDao.findByTelephone(telephone);

        if (member != null) {//是会员

                //遍历套餐id
                for (Integer setmealId : setmealIds) {

                    //获取会员id
                    Integer member_Id = member.getId();
                    //获取预约时间
                    Date date = DateUtils.parseString2Date(orderDate);
                    Order order = new Order(member_Id, date, setmealId);

                    List<Order> list = orderDao.findByCondition(order);

                    if (list != null && list.size() > 0) {
                        return new Result(false, MessageConstant.HAS_ORDERED);
                    }
                }

        } else {
            //4.判断用户是否为会员,不是会员的话直接注册
            member = new Member();
            member.setName((String) map.get("name"));
            member.setSex((String) map.get("sex"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setBirthday(DateUtils.parseString2Date((String) map.get("birthday")));
            member.setRegTime(new Date());

            memberDao.add(member);
        }

        //5.保存预约到数据库
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtils.parseString2Date(orderDate));
        order.setOrderType((String) map.get("orderType"));
        order.setOrderStatus(Order.ORDERSTATUS_NO);

        for (Integer setmealId : setmealIds) {

            order.setSetmealId(setmealId);
            orderDao.add(order);
            //6.预约成功,更改该日期的可预约人数
            orderSetting.setReservations(orderSetting.getReservations() + 1);
            orderSettingDao.editReservationsByOrderDate(orderSetting);

        }

        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    //确定预约
    @Override
    public void confirmOrder(Map map) {

        //根据订单的id修改订单的状态
        map.put("orderStatus",Order.ORDERSTATUS_YES);
        orderDao.updateOrderStatusById(map);

    }

    //取消预约
    @Override
    public void cancelOrder(Map map) throws Exception{

        //获取预约时间
        String orderDate = (String) map.get("orderDate");
        //该日期的预约设置对象
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        orderSetting.setReservations(orderSetting.getReservations() -1);
        //更新预约设置对象  已预约人数-1
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        //删除预约订单
        Integer id = (Integer) map.get("id");
        orderDao.deleteOrderById(id);
    }

    //批量确定预约
    @Override
    public void multiConfirmOrder(List<Map> list) {

        for (Map map : list) {

            //根据订单的id修改订单的状态
            map.put("orderStatus",Order.ORDERSTATUS_YES);
            orderDao.updateOrderStatusById(map);
        }
        
    }

    //批量取消预约
    @Override
    public void multiCancelOrder(List<Map> list) throws Exception{

        for (Map map : list) {

            //获取预约时间
            String orderDate = (String) map.get("orderDate");
            //该日期的预约设置对象
            OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
            orderSetting.setReservations(orderSetting.getReservations() -1);
            //更新预约设置对象  已预约人数-1
            orderSettingDao.editReservationsByOrderDate(orderSetting);

            //删除预约订单
            Integer id = (Integer) map.get("id");
            orderDao.deleteOrderById(id);
        }

    }
}
